package com.tupu.service.impl.dispatch;

import com.alibaba.druid.sql.visitor.functions.Trim;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tupu.common.PageResult;
import com.tupu.entity.dispatch.*;
import com.tupu.entity.dto.WarningEventFailurePlanDto;
import com.tupu.entity.neo4j.NodeSingle;
import com.tupu.entity.ocs.*;
import com.tupu.mapper.dispatch.*;
import com.tupu.mapper.ocs.*;
import com.tupu.service.dispatch.TbFilesService;
import com.tupu.service.dispatch.WarningEventService;
import com.tupu.util.FileUtil;
import com.tupu.util.Neo4jUtil;
import com.tupu.util.RegexUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WarningEventServiceImpl extends ServiceImpl<WarningEventMapper, WarningEvent> implements WarningEventService {

    @Autowired(required = false)
    private T0122IalmFactionMapper t0122IalmFactionMapper;

    @Autowired(required = false)
    private Neo4jUtil neo4jUtil;

    @Autowired(required = false)
    private T0121IalmFindexMapper t0121IalmFindexMapper;

    @Autowired(required = false)
    private T0125IalmWindexMapper t0125IalmWindexMapper;

    @Autowired(required = false)
    private T0003StationMapper t0003StationMapper;

    @Autowired(required = false)
    private T1211DeviceMapper t1211DeviceMapper;

    @Autowired(required = false)
    private T0420AlmhMapper t0420AlmhMapper;

    @Autowired(required = false)
    private WarningEventService warningEventService;

    @Autowired(required = false)
    private WarningEventFailurePlanMapper warningEventFailurePlanMapper;

    @Autowired(required = false)
    private WarningEventMapper warningEventMapper;

    @Autowired(required = false)
    private T1216DevicetypeMapper t1216DevicetypeMapper;

    @Autowired(required = false)
    private TbFilesService tbFilesService;

    @Autowired(required = false)
    private DadsBdsbtzMapper dadsBdsbtzMapper;

    @Autowired(required = false)
    private DadsJxdMapper dadsJxdMapper;

    @Autowired(required = false)
    private DadsCzpjxdMapper dadsCzpjxdMapper;

    @Autowired(required = false)
    private DadsCzpMapper dadsCzpMapper;

    @Autowired(required = false)
    private DadsSbqxMapper dadsSbqxMapper;

    @Autowired(required = false)
    private DadsYcxhclMapper dadsYcxhclMapper;

    //告警事件列表
    @Override
    public PageResult<WarningEvent> conditionSearch(Long page, Long size, String eventType, String station, String deviceType, String startTime, String endTime, String device) {
        QueryWrapper<WarningEvent> wrapper = new QueryWrapper<>();
        Page<WarningEvent> pageInfo = new Page<>(page, size);
        if (StringUtils.isNotEmpty(eventType)) {
            wrapper.eq("event_type", eventType);
        }
        if (StringUtils.isNotEmpty(station)) {
            wrapper.eq("station", station);
        }
        if (StringUtils.isNotEmpty(device)) {
            wrapper.like("device", device);
        }
        if (StringUtils.isNotEmpty(deviceType)) {
            wrapper.eq("device_type", deviceType);
        }
        if (startTime != null) {
            String time = startTime + " " + "00:00:00";
            wrapper.ge("time", time);
        }
        if (endTime != null) {
            String time = endTime + " " + "23:59:59";
            wrapper.le("time", time);
        }
        wrapper.orderByDesc("time");
        //分页
        Page<WarningEvent> eventPage = warningEventMapper.selectPage(pageInfo, wrapper);
        PageResult<WarningEvent> info = new PageResult<>();
        long total = eventPage.getTotal();
        info.setTotal(total);
        info.setList(eventPage.getRecords());
        info.setPage(page);
        info.setSize(size);
        info.setTotalPages((total / size + (total % size != 0 ? 1 : 0)));
        return info;
    }

    /**
     * 所有厂站
     *
     * @return
     */
    @Override
    @DS("oracle")
    public Map<String, Integer> findAllStation() {
        Map<String, Integer> map = new HashMap<>();
        List<T0003Station> stations = t0003StationMapper.selectList(null);
        for (T0003Station t : stations) {
            map.put(t.getC0003StationDesc(), t.getC0003StationNo());
        }
        return map;
    }

    /**
     * 设备类型
     *
     * @return
     */
    @Override
    @DS("oracle")
    public Map<String, String> findAllDeviceType() {
        Map<String, String> map = new HashMap<>();
        List<T1216Devicetype> types = t1216DevicetypeMapper.selectList(null);
        for (T1216Devicetype type : types) {
            if (null != type.getC1216Devtype()) {
                map.put(type.getC1216Devtypedesc(), type.getC1216Devtype());
            }
        }
        return map;
    }

    /**
     * 所有设备
     *
     * @return
     */
    @Override
    @DS("oracle")
    public Map<String, Integer> findAllDevice() {
        Map<String, Integer> map = new HashMap<>();
        List<T1211Device> deviceList = t1211DeviceMapper.selectList(null);
        for (T1211Device device : deviceList) {
            if (null != device.getC1211DEVID() && null != device.getC1211DEVDESC()) {
                map.put(device.getC1211DEVDESC(), device.getC1211DEVID());
            }
        }
        return map;
    }

    /**
     * 信号缺失
     *
     * @param event_id
     * @return
     */
    @Override
    @DS("oracle")
    public List<WarningEventMissData> findMissData(String event_id) {
        List<WarningEventMissData> list = new ArrayList<>();
        //判断事故或是异常
        char c = event_id.charAt(0);
        String station = "";
        String signalType = "";
        List<String> options = new ArrayList<>();
        if (c == 'F') {
            QueryWrapper<T0122IalmFaction> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("C0122_FCode", event_id);
            List<T0122IalmFaction> ialmFactions = t0122IalmFactionMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(ialmFactions)) {
                for (T0122IalmFaction t : ialmFactions) {
                    String desc = t.getC0122ActionDesc();
                    String[] split = desc.split("\\s+");
                    List<String> collect = Arrays.stream(split).collect(Collectors.toList());

                    signalType = collect.get(3);
                    station = collect.get(2);
                    StringBuffer buffer = new StringBuffer();
                    String s = buffer.append(collect.get(3)).append(collect.get(4)).toString();
                    //System.out.println(desc);
                    options.add(s);
                }
                List<String> result = findMatchingOptions(options);
                for (String option : result) {
                    // System.out.println(option);
                    options.remove(option);
                }
                // System.out.println(options);
                if (options != null) {
                    for (String s : options) {
                        WarningEventMissData missData = new WarningEventMissData();
                        String deviceType = s.substring(0, s.length() - 2);
                        String eventDescribe = s.substring(s.length() - 2);
                        missData.setDeviceType(deviceType);
                        missData.setStation(station);
                        missData.setSignalType(signalType);
                        missData.setEventDescribe(eventDescribe);
                        list.add(missData);
                    }
                }
            }
            return list;
        }
        if (c == 'S') {
            //对应事项从T0420_ALMH里获取，要求：
            //1、c0125_devkey=c0420_dev_key
            QueryWrapper<T0125IalmWindex> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("C0125_WCode", event_id);
            List<T0125IalmWindex> windexList = t0125IalmWindexMapper.selectList(queryWrapper3);
            if (CollectionUtils.isNotEmpty(windexList)) {
                for (T0125IalmWindex t042 : windexList) {
                    String c0125_devKey = t042.getC0125DevKey();
                    QueryWrapper<T0420Almh> queryWrapper4 = new QueryWrapper<>();
                    queryWrapper4.eq("C0420_DEV_KEY", c0125_devKey);

                    if (t042.getC0125End() == 0) {
                        queryWrapper4.eq("C0420_DATE", t042.getC0125Start());
                    } else {
                        //小于等于
                        queryWrapper4.le("C0420_DATE", t042.getC0125End());
                        //大于等于
                        queryWrapper4.ge("C0420_DATE", t042.getC0125Start());
                    }
                    List<T0420Almh> t0420Almhs = t0420AlmhMapper.selectList(queryWrapper4);
                    for (T0420Almh al : t0420Almhs) {
                        String text = al.getC0420AlmText();
                        String[] split = text.split("\\s+");
                        List<String> collect = Arrays.stream(split).collect(Collectors.toList());

                        try {
                            station = collect.get(3);
                            StringBuffer buffer = new StringBuffer();
                            String s = buffer.append(collect.get(4)).append(collect.get(5)).toString();
                            options.add(s);
                        } catch (Exception e) {
                            return list;
                        }
                    }
                    List<String> result = findMatchingOptions(options);

                    for (String option : result) {
                        //System.out.println(option);
                        options.remove(option);
                    }
                    //System.out.println(options);
                    if (options != null) {
                        for (String s : options) {
                            WarningEventMissData missData = new WarningEventMissData();
                            String deviceType = s.substring(0, s.length() - 2);
                            String eventDescribe = s.substring(s.length() - 2);
                            //missData.setDeviceType(deviceType);
                            missData.setStation(station);
                            missData.setSignalType(signalType);
                            missData.setEventDescribe(eventDescribe);
                            list.add(missData);
                        }
                    }
                }
            }
            return list;
        }
        return list;
    }

    /**
     * 查询关联信号未匹配的句子
     *
     * @param options
     * @return
     */
    private List<String> findMatchingOptions(List<String> options) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < options.size() - 1; i++) {
            for (int j = i + 1; j < options.size(); j++) {
                if (options.get(i).substring(0, options.get(i).length() - 2).equals(options.get(j).substring(0, options.get(j).length() - 2))) {
                    if (options.get(i).substring(options.get(i).length() - 2).equals("动作") && options.get(j).substring(options.get(j).length() - 2).equals("复归")) {
                        result.add(options.get(i));
                        result.add(options.get(j));
                    }
                    if (options.get(i).substring(options.get(i).length() - 2).equals("动作") && options.get(j).substring(options.get(j).length() - 2).equals("恢复")) {
                        result.add(options.get(i));
                        result.add(options.get(j));
                    }
                    if (options.get(i).substring(options.get(i).length() - 2).equals("复归") && options.get(j).substring(options.get(j).length() - 2).equals("动作")) {
                        result.add(options.get(i));
                        result.add(options.get(j));
                    }
                    if (options.get(i).substring(options.get(i).length() - 2).equals("分闸分闸") && options.get(j).substring(options.get(j).length() - 2).equals("合闸")) {
                        result.add(options.get(i));
                        result.add(options.get(j));
                    }
                    if (options.get(i).substring(options.get(i).length() - 2).equals("合闸") && options.get(j).substring(options.get(j).length() - 2).equals("分闸")) {
                        result.add(options.get(i));
                        result.add(options.get(j));
                    }
                    if (options.get(i).substring(options.get(i).length() - 2).equals("断开") && options.get(j).substring(options.get(j).length() - 2).equals("闭合")) {
                        result.add(options.get(i));
                        result.add(options.get(j));
                    }
                    if (options.get(i).substring(options.get(i).length() - 2).equals("闭合") && options.get(j).substring(options.get(j).length() - 2).equals("断开")) {
                        result.add(options.get(i));
                        result.add(options.get(j));
                    }
                }
            }
        }
        return result;
    }

    /**
     * 关联的告警信号 详情
     *
     * @param event_id
     * @return
     */
    @Override
    @DS("oracle")
    public List<WarningEventContactSignalData> findByEventId(String event_id) {
        List<WarningEventContactSignalData> dataList = new ArrayList<>();
        char c = event_id.charAt(0);
        if (c == 'F') {
            QueryWrapper<T0122IalmFaction> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("C0122_FCODE", event_id);
            List<T0122IalmFaction> list = t0122IalmFactionMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                for (T0122IalmFaction f : list) {
                    String desc = f.getC0122ActionDesc();
                    //String desc = "2023/08/02 12:00:19           保护信号  南海站                35kV码头乙线362保护动作   动作";
                    String[] split = desc.split("\\s+");
                    List<String> collect = Arrays.stream(split).collect(Collectors.toList());
                    WarningEventContactSignalData data = new WarningEventContactSignalData();
                    //data.setContactId(event_id);
                    data.setTime(collect.get(0) + " " + collect.get(1));
                    data.setStation(collect.get(3));
                    data.setDeviceType(collect.get(2));
                    data.setEventDescribe(collect.get(4));
                    dataList.add(data);
                }
            }
            return dataList;
        } else {
            //对应事项从T0420_ALMH里获取，要求：
            //1、c0125_devkey=c0420_dev_key
            //2、如果C0125_END为0，c0420_date=C0125_START;否则C0125_START<=c0420_date and c0420_date<=C0125_END
            QueryWrapper<T0125IalmWindex> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("C0125_WCODE", event_id);
            //queryWrapper.eq("C0125_DevKey",event_id);
            List<T0125IalmWindex> windexList = t0125IalmWindexMapper.selectList(queryWrapper);
            //System.out.println(windexList.size());
            //System.out.println(windexList);
            if (CollectionUtils.isNotEmpty(windexList)) {
                for (T0125IalmWindex t : windexList) {
                    String c0125_devKey = t.getC0125DevKey();
                    QueryWrapper<T0420Almh> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("C0420_DEV_KEY", c0125_devKey);
                    if (t.getC0125End() == 0) {
                        queryWrapper1.eq("C0420_DATE", t.getC0125Start());
                    } else {
                        //小于等于
                        queryWrapper1.le("C0420_DATE", t.getC0125End());
                        //大于等于
                        queryWrapper1.ge("C0420_DATE", t.getC0125Start());
                    }
                    List<T0420Almh> t0420Almhs = t0420AlmhMapper.selectList(queryWrapper1);
                    for (T0420Almh al : t0420Almhs) {
                        String text = al.getC0420AlmText();
                        String[] split = text.split("\\s+");
                        List<String> collect = Arrays.stream(split).collect(Collectors.toList());
                        WarningEventContactSignalData data = new WarningEventContactSignalData();
                        data.setTime(collect.get(0) + " " + collect.get(1));
                        //data.setSignalType(collect.get(2));
                        data.setStation(collect.get(2));
                        data.setDeviceType(collect.get(3));
                        data.setEventDescribe(collect.get(4));
                        dataList.add(data);
                    }
                }
            }
            return dataList;
        }
    }

    /**
     * 匹配最合适的故障预案
     *
     * @param event_id
     * @param node_id
     * @return
     * @throws IOException
     */
    @Override
    public WarningEventFailurePlan recommendPlan(String event_id, Long node_id) throws IOException {
        node_id = 2L;
        WarningEventFailurePlan plan = new WarningEventFailurePlan();
        //String s = "2023/06/19 00:08:51      保护信号  马踏站    110kV曙马线1275智能终端空调故障告警 恢复";
        QueryWrapper<T0121IalmFindex> wrapper = new QueryWrapper<>();
        wrapper.eq("C0121_FCODE", event_id);
        T0121IalmFindex one = t0121IalmFindexMapper.selectOne(wrapper);
        String desc = one.getC0121FaultDesc();
        String[] split = desc.split("\\s+");
        List<String> collect = Arrays.stream(split).collect(Collectors.toList());
        String stationName = collect.get(0);
        String describe = collect.get(1);

        List<NodeSingle> nodesList = neo4jUtil.vagueSearchNodeByName(stationName, node_id);

        //分词
        StringReader reader = new StringReader(describe);
        IKSegmenter segmenter = new IKSegmenter(reader, true);
        Lexeme lexeme;

        List<String> words = new ArrayList<>();
        List<String> sentences = new ArrayList<>();

        while ((lexeme = segmenter.next()) != null) {
            //System.out.println("ik:" + lexeme.getLexemeText());
            words.add(lexeme.getLexemeText());
        }

        for (NodeSingle node : nodesList) {
            Map<String, Object> attrs = node.getAttrs();
            for (Map.Entry<String, Object> entry : attrs.entrySet()) {
                if (entry.getKey().equals("故障设置")) {
                    String value = entry.getValue().toString();
                    sentences.add(value);
                }
            }
        }

        String bestMatch = findBestMatch(words, sentences);
        log.info("最匹配的句子是：" + bestMatch);
        List<NodeSingle> nodeList = neo4jUtil.vagueSearchNodeByAttrs(stationName, bestMatch, node_id);
        if (nodeList.size() == 0) {
            return plan;
        }
        for (int i = 0; i < 1; i++) {
            for (NodeSingle node : nodeList) {
                Map<String, Object> attrs = node.getAttrs();
                plan.setName(attrs.get("name").toString());
                plan.setNumber(attrs.get("uid").toString());
                plan.setPlace(attrs.get("负责单位").toString());
                plan.setCreateDate(attrs.get("创建日期").toString());
                plan.setProducer(attrs.get("编制人").toString());
                plan.setAuditor(attrs.get("审核人").toString());
                plan.setSummary(attrs.get("概述").toString());
                plan.setBeforeWay(attrs.get("事前运行方式").toString());
                plan.setFaultSetting(attrs.get("故障设置").toString());
                plan.setAfterWay(attrs.get("事后运行方式").toString());
                plan.setAfterRisk(attrs.get("事后风险分析").toString());
                plan.setTotalNote(attrs.get("主要控制目标/南网总调").toString());
                plan.setMiddleNote(attrs.get("主要控制目标/广东中调").toString());
                plan.setRegulation(attrs.get("主要控制目标/茂名调控").toString());
                plan.setProcess(attrs.get("事故处理过程及要点").toString());
                plan.setReportedPlace(attrs.get("事故信息上报/上报单位").toString());
                plan.setReportedObject(attrs.get("事故信息上报/上报内容").toString());
                plan.setReportedContent(attrs.get("事故信息上报/上报对象").toString());
                plan.setPublishPlace(attrs.get("事故信息发布/发布单位").toString());
                plan.setPublishObject(attrs.get("事故信息发布/发布内容").toString());
                plan.setPublishContent(attrs.get("事故信息发布/发布对象").toString());
                plan.setAssess(attrs.get("事故影响评估").toString());
                plan.setRemarks(attrs.get("备注").toString());

                // plan.setCategory(attrs.get("类别").toString());
                // plan.setLevel(attrs.get("级别").toString());
            }
        }
        return plan;
    }

    /**
     * 使用字符串匹配的算法 查询最佳匹配
     *
     * @param words
     * @param sentences
     * @return
     */
    private static String findBestMatch(List<String> words, List<String> sentences) {
        String bestMatch = null;
        int maxMatchCount = 0;
        for (String sentence : sentences) {
            int matchCount = 0;

            for (String word : words) {
                if (sentence.contains(word)) {
                    matchCount++;
                }
            }
            if (matchCount > maxMatchCount) {
                maxMatchCount = matchCount;
                bestMatch = sentence;
            }
        }
        return bestMatch;
    }

    /**
     * 故障预案识别导入
     *
     * @param file
     * @param eventId
     * @throws Exception
     */
    @Override
    public void uploadWordPlan(MultipartFile file, String eventId) throws Exception {
        //上传导入
        String filename = file.getOriginalFilename();
        String[] fileNames = filename.split("\\.");
        // 创建一个临时文件,方法结束后就会删除
        File newFile = File.createTempFile(fileNames[0], "." + fileNames[1]);
        InputStream inputStream = file.getInputStream();
        FileUtils.copyInputStreamToFile(inputStream, newFile);
        String absolutePath = newFile.getAbsolutePath();
        //Map<String, Object> map = new HashMap<>();
        FileInputStream in = new FileInputStream(absolutePath);//载入文档
        // 处理docx格式 即office2007以后版本
        //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
        XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
        Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
        int tableCount = 0;
        for (XWPFTable table : xwpf.getTables()) {
            tableCount++;
        }
        //System.out.println("表格总数：" + tableCount);
        while (it.hasNext()) {
            Map<String, Object> map = new HashMap<>();
            XWPFTable table = it.next();
            List<XWPFTableRow> rows = table.getRows();
            //读取每一行数据
            for (int i = 0; i < rows.size(); i++) {
                XWPFTableRow row = rows.get(i);
                //读取每一列数据
                List<XWPFTableCell> cells = row.getTableCells();
                String key1 = null;
                String key2 = "";
                String key3 = "";
                String key4;
                String key5 = "";

                String value1 = "";
                String value2 = "";
                String value3 = "";
                String value5 = "";

                for (int j = 0; j < cells.size(); j++) {
                    XWPFTableCell cell = cells.get(j);
                    if (cells.size() == 2) {
                        if (j == 0) {
                            key1 = cell.getText();
                        } else {
                            value1 = cell.getText().trim();
                        }
                    }

                    if (cells.size() == 4) {
                        if (j == 0) {
                            key2 = cell.getText();
                        } else if (j == 1) {
                            value2 = cell.getText().trim();
                        }
                        if (j == 2) {
                            key3 = cell.getText();
                        } else if (j == 3) {
                            value3 = cell.getText().trim();
                        }
                    }

                    if (cells.size() == 3) {
                        if (j == 1) {
                            key4 = cell.getText();
                            if (key4.equals("南网总调") || key4.equals("广东中调") || key4.equals("茂名调控")) {
                                key5 = "主要控制目标" + "/" + key4;
                            }
                            if (key4.equals("上报单位") || key4.equals("上报对象") || key4.equals("上报内容")) {
                                key5 = "事故信息上报" + "/" + key4;
                            }
                            if (key4.equals("发布单位") || key4.equals("发布对象") || key4.equals("发布内容")) {
                                key5 = "事故信息发布" + "/" + key4;
                            }
                        } else if (j == 2) {
                            value5 = cell.getText();
                        }
                    }
                }
                map.put(key1, value1);
                map.put(key2, value2);
                map.put(key3, value3);
                map.put(key5, value5);
                map.remove(null);
                map.remove("");
            }
            NodeSingle node = new NodeSingle();
            node.setAttrs(map);
            WarningEventFailurePlan plan = new WarningEventFailurePlan();
            Map<String, Object> attrs = node.getAttrs();
            String name = null;
            if (attrs.containsKey("事故预案名称")) {
                name = attrs.get("事故预案名称").toString();
            }
            plan.setName(name);
            for (String s : attrs.keySet()) {
                if (s.contains("编号")) {
                    plan.setNumber(attrs.get(s).toString());
                }
            }
            if (attrs.containsKey("负责单位")) {
                plan.setPlace(attrs.get("负责单位").toString());
            }
            if (attrs.containsKey("创建日期")) {
                plan.setCreateDate(attrs.get("创建日期").toString());
            }
            if (attrs.containsKey("编制人")) {
                plan.setProducer(attrs.get("编制人").toString());
            }
            if (attrs.containsKey("审核人")) {
                plan.setAuditor(attrs.get("审核人").toString());
            }
            if (attrs.containsKey("概述")) {
                plan.setSummary(attrs.get("概述").toString());
            }
            if (attrs.containsKey("事前运行方式")) {
                plan.setBeforeWay(attrs.get("事前运行方式").toString());
            }
            if (attrs.containsKey("故障设置")) {
                plan.setFaultSetting(attrs.get("故障设置").toString());
            }
            if (attrs.containsKey("事后运行方式")) {
                plan.setAfterWay(attrs.get("事后运行方式").toString());
            }
            if (attrs.containsKey("事后风险分析")) {
                plan.setAfterRisk(attrs.get("事后风险分析").toString());
            }
            if (attrs.containsKey("主要控制目标/南网总调")) {
                plan.setTotalNote(attrs.get("主要控制目标/南网总调").toString());
            }
            if (attrs.containsKey("主要控制目标/广东中调")) {
                plan.setMiddleNote(attrs.get("主要控制目标/广东中调").toString());
            }
            if (attrs.containsKey("主要控制目标/茂名调控")) {
                plan.setRegulation(attrs.get("主要控制目标/茂名调控").toString());
            }
            if (attrs.containsKey("事故处理过程及要点")) {
                plan.setProcess(attrs.get("事故处理过程及要点").toString());
            }
            if (attrs.containsKey("事故信息上报/上报单位")) {
                plan.setReportedPlace(attrs.get("事故信息上报/上报单位").toString());
            }
            if (attrs.containsKey("事故信息上报/上报内容")) {
                plan.setReportedObject(attrs.get("事故信息上报/上报内容").toString());
            }
            if (attrs.containsKey("事故信息上报/上报对象")) {
                plan.setReportedContent(attrs.get("事故信息上报/上报对象").toString());
            }
            if (attrs.containsKey("事故信息发布/发布单位")) {
                plan.setPublishPlace(attrs.get("事故信息发布/发布单位").toString());
            }
            if (attrs.containsKey("事故信息发布/发布内容")) {
                plan.setPublishObject(attrs.get("事故信息发布/发布内容").toString());
            }
            if (attrs.containsKey("事故信息发布/发布对象")) {
                plan.setPublishContent(attrs.get("事故信息发布/发布对象").toString());
            }
            if (attrs.containsKey("事故影响评估")) {
                plan.setAssess(attrs.get("事故影响评估").toString());
            }
            if (attrs.containsKey("备注")) {
                plan.setRemarks(attrs.get("备注").toString());
            }
            //类别
            if (name.contains("母线")) {
                plan.setCategory(2);
            }
            if (name.contains("全站")) {
                plan.setCategory(1);
            } else {
                plan.setCategory(3);
            }
            //级别
            String number = plan.getNumber();
            if (number.contains("较大")) {
                plan.setLevel(6);
            }
            if (number.contains("一般")) {
                plan.setLevel(7);
            }
            if (number.contains("一级")) {
                plan.setLevel(1);
            }
            if (number.contains("二级")) {
                plan.setLevel(2);
            }
            if (number.contains("三级")) {
                plan.setLevel(3);
            }
            if (number.contains("四级")) {
                plan.setLevel(4);
            }
            if (number.contains("五级")) {
                plan.setLevel(5);
            }

            //更新时间
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(date);
            plan.setUpdateTime(time);
            //厂站 分词
            StringReader reader = new StringReader(name);
            IKSegmenter ik = new IKSegmenter(reader, true);
            Lexeme lex;
            while ((lex = ik.next()) != null) {
                String text = lex.getLexemeText();
                if (text.contains("站") && !text.equals("全站")) {
                    //System.out.println("==========" + text);
                    plan.setStation(text);
                }
            }
            //状态（未入预案库）
            plan.setStateId(0);
            warningEventFailurePlanMapper.insert(plan);
            tbFilesService.insertTbFileByFile(file, plan.getPlanId().toString());
            WarningEvent event = warningEventMapper.selectById(eventId);
            event.setPlan(1);
            warningEventMapper.updateById(event);
        }
    }

    @Override
    public List<WarningEventFailurePlanDto> recommend(String eventId) {
        WarningEvent warningEvent = warningEventMapper.selectById(eventId);
        String station = warningEvent.getStation();
        //String device = warningEvent.getDevice();
        List<WarningEventFailurePlanDto> dtoList = new ArrayList<>();
        QueryWrapper<WarningEventFailurePlan> wrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(station)) {
            return dtoList;
        }
        wrapper.like("name", station);
        //if (StringUtils.isNotEmpty(device)) {
        //  wrapper.like("before_way", device);
        // }
        List<WarningEventFailurePlan> list = warningEventFailurePlanMapper.selectList(wrapper);

        if (CollectionUtils.isNotEmpty(list)) {
            for (WarningEventFailurePlan plan : list) {
                if (StringUtils.isEmpty(plan.getStation())) {
                    plan.setStation(station);
                }
                WarningEventFailurePlanDto dto = new WarningEventFailurePlanDto();
                dto.setPlanId(plan.getPlanId());
                dto.setPlanName(plan.getName());
                dto.setDevice(plan.getDevice());
                dto.setStation(station);
                dto.setCreateName(plan.getProducer());
                dto.setUpdateTime(plan.getUpdateTime());
                Integer cate = plan.getCategory();
                if (null != cate) {
                    if (cate == 1) {
                        dto.setCategory("站点");
                    }
                    if (cate == 2) {
                        dto.setCategory("母线");
                    }
                    if (cate == 3) {
                        dto.setCategory("线路");
                    }
                }
                Integer lev = plan.getLevel();
                if (null != lev) {
                    if (lev == 1) {
                        dto.setLevel("一级");
                    }
                    if (lev == 2) {
                        dto.setLevel("二级");
                    }
                    if (lev == 3) {
                        dto.setLevel("三级");
                    }
                    if (lev == 4) {
                        dto.setLevel("四级");
                    }
                    if (lev == 5) {
                        dto.setLevel("五级");
                    }
                    if (lev == 6) {
                        dto.setLevel("重大");
                    }
                    if (lev == 7) {
                        dto.setLevel("一般");
                    }
                }
                dtoList.add(dto);
            }
        }
        dtoList.sort(Comparator.comparing(WarningEventFailurePlanDto::getUpdateTime).reversed());
        return dtoList;
    }

    @Override
    public PageResult findDispatchByEventId(String eventId, Long page, Long size) {
        PageResult<WarningEventDispatchData> info = new PageResult<>();
        List<WarningEventDispatchData> list = new ArrayList<>();
        WarningEvent event = warningEventMapper.selectById(eventId);
        String device = event.getDevice();
        String station = event.getStation();

        //变电设备跳闸
        QueryWrapper<DadsBdsbtz> wrapper = new QueryWrapper<>();
        //wrapper.eq("EQUIP_NAME", device);
        wrapper.eq("STATION", station);
        List<DadsBdsbtz> dadsBdsbtz = dadsBdsbtzMapper.selectList(wrapper);
        for (DadsBdsbtz d : dadsBdsbtz) {
            WarningEventDispatchData data = new WarningEventDispatchData();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            data.setTime(sdf.format(d.getWriteTime()));
            data.setAbnormalId(d.getId());
            data.setStation(d.getStation());
            data.setPwrgridName(d.getPwrgridName());
            data.setDeviceName(d.getEquipName());
            data.setLogType("变电设备跳闸");
            data.setSjnr(d.getSjnr());
            data.setBzzysy(d.getBzzysy());
            data.setRemark(d.getRemark());
            list.add(data);
        }
        //设备缺陷
        QueryWrapper<DadsSbqx> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("SUBSTATION", station);
        //wrapper2.eq("EQUIP_NAME", device);
        List<DadsSbqx> dadsSbqxs = dadsSbqxMapper.selectList(wrapper2);
        for (DadsSbqx sbqx : dadsSbqxs) {
            WarningEventDispatchData data = new WarningEventDispatchData();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            data.setTime(sdf.format(sbqx.getWriteTime()));
            data.setAbnormalId(sbqx.getId());
            data.setStation(sbqx.getSubstation());
            data.setPwrgridName(sbqx.getPwrgridName());
            data.setDeviceName(sbqx.getEquipName());
            data.setLogType("设备缺陷");
            if (StringUtils.isNotEmpty(sbqx.getDefectImpact())) {
                data.setSjnr(sbqx.getDefectImpact());
            }
            data.setBzzysy(sbqx.getBzzysy());
            data.setRemark(sbqx.getRemark());
            list.add(data);
        }

        //异常信号处理
        QueryWrapper<DadsYcxhcl> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("STATION_NAME", station);
        //wrapper3.like("ABNORMAL_SIGNAL", device);

        List<DadsYcxhcl> dadsYcxhcls = dadsYcxhclMapper.selectList(wrapper3);
        for (DadsYcxhcl ycxhcl : dadsYcxhcls) {
            WarningEventDispatchData data = new WarningEventDispatchData();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            data.setTime(sdf.format(ycxhcl.getWriteTime()));
            data.setAbnormalId(ycxhcl.getId());
            data.setStation(ycxhcl.getStationName());
            data.setPwrgridName(ycxhcl.getPwrgridName());
            data.setDeviceName(ycxhcl.getEquipmentName());
            data.setLogType("异常信号处理");
            if (StringUtils.isNotEmpty(ycxhcl.getAbnormalSignal())) {
                data.setSjnr(ycxhcl.getAbnormalSignal());
            }
            data.setBzzysy(ycxhcl.getBzzysy());
            data.setRemark(ycxhcl.getRemark());
            list.add(data);
        }

        int total = list.size();
        list.sort(Comparator.comparing(WarningEventDispatchData::getTime).reversed());
        info.setTotal((long) total);
        info.setList(list);
        info.setPage(page);
        info.setSize(size);
        info.setTotalPages((total / size + (total % size != 0 ? 1 : 0)));
        return info;
    }

    @Override
    public List<WarningEventDispatchData> findDispatchListByEventIdNoPage(String eventId) {
        List<WarningEventDispatchData> list = new ArrayList<>();
        WarningEvent event = warningEventMapper.selectById(eventId);
        String device = event.getDevice();
        String station = event.getStation();

        //变电设备跳闸
        QueryWrapper<DadsBdsbtz> wrapper = new QueryWrapper<>();
        //wrapper.eq("EQUIP_NAME", device);
        wrapper.eq("STATION", station);
        List<DadsBdsbtz> dadsBdsbtz = dadsBdsbtzMapper.selectList(wrapper);
        for (DadsBdsbtz d : dadsBdsbtz) {
            WarningEventDispatchData data = new WarningEventDispatchData();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            data.setTime(sdf.format(d.getWriteTime()));
            data.setAbnormalId(d.getId());
            data.setStation(d.getStation());
            data.setPwrgridName(d.getPwrgridName());
            data.setDeviceName(d.getEquipName());
            data.setLogType("变电设备跳闸");
            data.setSjnr(d.getSjnr());
            data.setBzzysy(d.getBzzysy());
            data.setRemark(d.getRemark());
            list.add(data);
        }
        //设备缺陷
        QueryWrapper<DadsSbqx> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("SUBSTATION", station);
        //wrapper2.eq("EQUIP_NAME", device);
        List<DadsSbqx> dadsSbqxs = dadsSbqxMapper.selectList(wrapper2);
        for (DadsSbqx sbqx : dadsSbqxs) {
            WarningEventDispatchData data = new WarningEventDispatchData();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            data.setTime(sdf.format(sbqx.getWriteTime()));
            data.setAbnormalId(sbqx.getId());
            data.setStation(sbqx.getSubstation());
            data.setPwrgridName(sbqx.getPwrgridName());
            data.setDeviceName(sbqx.getEquipName());
            data.setLogType("设备缺陷");
            if (StringUtils.isNotEmpty(sbqx.getDefectImpact())) {
                data.setSjnr(sbqx.getDefectImpact());
            }
            data.setBzzysy(sbqx.getBzzysy());
            data.setRemark(sbqx.getRemark());
            list.add(data);
        }

        //异常信号处理
        QueryWrapper<DadsYcxhcl> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("STATION_NAME", station);
        //wrapper3.like("ABNORMAL_SIGNAL", device);
        List<DadsYcxhcl> dadsYcxhcls = dadsYcxhclMapper.selectList(wrapper3);
        for (DadsYcxhcl ycxhcl : dadsYcxhcls) {
            WarningEventDispatchData data = new WarningEventDispatchData();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            data.setTime(sdf.format(ycxhcl.getWriteTime()));
            data.setAbnormalId(ycxhcl.getId());
            data.setStation(ycxhcl.getStationName());
            data.setPwrgridName(ycxhcl.getPwrgridName());
            data.setDeviceName(ycxhcl.getEquipmentName());
            data.setLogType("异常信号处理");
            if (StringUtils.isNotEmpty(ycxhcl.getAbnormalSignal())) {
                data.setSjnr(ycxhcl.getAbnormalSignal());
            }
            data.setBzzysy(ycxhcl.getBzzysy());
            data.setRemark(ycxhcl.getRemark());
            list.add(data);
        }
        return list;
    }

    /**
     * 使用站名、设备关联检修单
     *
     * @param eventId
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageResult findJxdByEventId(String eventId, Long page, Long size) {
        WarningEvent event = warningEventMapper.selectById(eventId);
        List<WarningEventOverhaul> list = new ArrayList<>();
        PageResult<WarningEventOverhaul> info = new PageResult<>();
        String device = event.getDevice();
        String station = event.getStation();
        if (StringUtils.isNotEmpty(station)) {
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.like("TDJXSB", station);
            List<DadsJxd> jxdList = dadsJxdMapper.selectList(wrapper);
            for (DadsJxd jxd : jxdList) {
                WarningEventOverhaul overhaul = new WarningEventOverhaul();
                //id
                overhaul.setOverhaulId(jxd.getId());
                //编号
                overhaul.setIdentifier(jxd.getSqdbh());
                //检修类型
                overhaul.setOverhaulType(jxd.getJxlb());
                //申请单位
                overhaul.setApplicant(jxd.getSqdw());
                //提交时间
                Date date = jxd.getTjsj();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(date);
                overhaul.setFillingDate(format);
                //申请负责人
                overhaul.setFillingPeople(jxd.getSqfzr());
                //联系电话
                overhaul.setPhone(jxd.getSqrlxdh());
                //工作内容
                overhaul.setWorkContent(jxd.getGznr());
                list.add(overhaul);
            }
            List<WarningEventOverhaul> newList = list.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());
            newList.sort(Comparator.comparing(WarningEventOverhaul::getFillingDate).reversed());
            int total = list.size();
            info.setTotal((long) total);
            info.setList(newList);
            info.setPage(page);
            info.setSize(size);
            info.setTotalPages((total / size + (total % size != 0 ? 1 : 0)));
            return info;
        }
        return info;
    }

    /**
     * 使用站名、设备关联操作票
     *
     * @param eventId
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageResult findCzpByEventId(String eventId, Long page, Long size) {
        WarningEvent event = warningEventMapper.selectById(eventId);
        List<WarningEventOperateTicket> list = new ArrayList<>();
        PageResult<WarningEventOperateTicket> result = new PageResult<>();
        //String device = event.getDevice();
        String station = event.getStation();
        if (StringUtils.isNotEmpty(station)) {
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.like("TDJXSB", station);
            List<DadsJxd> jxdList = dadsJxdMapper.selectList(wrapper);
            if (null != jxdList) {
                for (DadsJxd d : jxdList) {
                    QueryWrapper<DadsCzpjxd> wrapper2 = new QueryWrapper<>();
                    wrapper2.eq("JXDID", d.getId());
                    List<DadsCzpjxd> czpList = dadsCzpjxdMapper.selectList(wrapper2);
                    for (DadsCzpjxd czp : czpList) {
                        String czpid = czp.getCzpid();
                        DadsCzp dadsCzp = dadsCzpMapper.selectById(czpid);
                        if (null != dadsCzp) {
                            WarningEventOperateTicket ticket = new WarningEventOperateTicket();
                            ticket.setTicketNum(dadsCzp.getCzpbh());
                            ticket.setFillTicketPeople(dadsCzp.getNpr());
                            Integer lx = dadsCzp.getLx();
                            if (lx == 0) {
                                ticket.setType("逐项令");
                            }
                            if (lx == 1) {
                                ticket.setType("综合令");
                            }
                            if (lx == 2) {
                                ticket.setType("单项令");
                            }
                            ticket.setOperatePurpose(dadsCzp.getCzmd());
                            list.add(ticket);
                        }
                    }
                }
            }
            List<WarningEventOperateTicket> czpList = list.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());
            //czpList.sort(Comparator.comparing(WarningEventOperateTicket::getFillingDate).reversed());
            int total = czpList.size();
            result.setTotal((long) total);
            result.setList(czpList);
            result.setPage(page);
            result.setSize(size);
            result.setTotalPages((total / size + (total % size != 0 ? 1 : 0)));
            return result;
        }
        return result;
    }

    @Override
    public WarningEventFailurePlan findPlanByPlanId(String planId) {
        WarningEventFailurePlan plan = warningEventFailurePlanMapper.selectById(planId);
        return plan;
    }

    public void findexAnalysis(Integer localDate) {
        QueryWrapper<T0121IalmFindex> queryWrapper = new QueryWrapper<>();
        //刷新所有列表
        //queryWrapper.like("C0121_FAULTDESC", "重合不成功").or().like("C0121_FAULTDESC", "无相关重合信息").or().like("C0121_FAULTDESC", "无相关重合闸信息").or().like("C0121_FAULTDESC", "重合闸失败");
        queryWrapper.eq("C0121_YMD", localDate)
                .and(wrapper -> wrapper.like("C0121_FAULTDESC", "重合不成功")
                        .or()
                        .like("C0121_FAULTDESC", "无相关重合信息")
                        .or()
                        .like("C0121_FAULTDESC", "无相关重合闸信息")
                        .or()
                        .like("C0121_FAULTDESC", "重合闸失败"));

        List<T0121IalmFindex> t0121IalmFindexList = t0121IalmFindexMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(t0121IalmFindexList)) {
            for (T0121IalmFindex t0121 : t0121IalmFindexList) {
                WarningEvent event = new WarningEvent();
                //主键id
                event.setEventId(t0121.getC0121FCode());
                //类型
                event.setEventType("事故告警");
                //时间
                String ymd = t0121.getC0121YMD().toString();
                String hmsms = t0121.getC0121HMSMS().toString();
                hmsms = String.format("%9s", hmsms).replace(" ", "0");
                StringBuffer buffer = new StringBuffer();
                buffer.append(ymd, 0, 4).append("-").append(ymd, 4, 6).append("-").append(ymd, 6, 8).append(" ").append(hmsms, 0, 2).append(":").append(hmsms, 2, 4).append(":").append(hmsms, 4, 6);
                event.setTime(buffer.toString());

                String c0121Substation = t0121.getC0121Substation();
                if (!StringUtils.isEmpty(c0121Substation)) {
                    QueryWrapper<T0003Station> wrapper1 = new QueryWrapper<>();
                    //wrapper1.eq("C0003_STATION_NAME", c0121Substation);
                    wrapper1.apply("TRIM(C0003_STATION_NAME) = {0}", c0121Substation);
                    T0003Station t0003Station = t0003StationMapper.selectOne(wrapper1);
                    if (null != t0003Station) {
                        event.setStation(t0003Station.getC0003StationDesc());
                    }
                }
                //设备
                Integer c0121FaultDevId = t0121.getC0121FaultDevId();
                QueryWrapper<T1211Device> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("C1211_DEVID", c0121FaultDevId);
                T1211Device t1211Device = t1211DeviceMapper.selectOne(wrapper2);
                if (t1211Device != null) {
                    event.setDevice(t1211Device.getC1211DEVDESC());
                }
                //设备类型
                if (t1211Device != null) {
                    String devtype = t1211Device.getC1216DEVTYPE();
                    QueryWrapper<T1216Devicetype> wrapper = new QueryWrapper<>();
                    wrapper.eq("C1216_DEVTYPE", devtype);
                    T1216Devicetype devicetype = t1216DevicetypeMapper.selectOne(wrapper);
                    if (null != devicetype) {
                        event.setDeviceType(devicetype.getC1216Devtypedesc());
                    }
                }
                //描述
                String desc = t0121.getC0121FaultDesc();
                String[] split = desc.split("\\s+");
                List<String> collect = Arrays.stream(split).collect(Collectors.toList());
                if (collect.size() == 1) {
                    event.setEventDescribe(collect.get(0));
                }
                if (collect.size() == 2) {
                    try {
                        event.setEventDescribe(collect.get(1));
                        event.setStation(collect.get(0));
                    } catch (Exception e) {
                        String station = RegexUtil.matchFirstTrim(desc, ".*站");
                        event.setStation(station);
                        String des = desc.replace(station, "");
                        event.setEventDescribe(des);
                    }
                }
                //推荐的告警事件
                List<WarningEventFailurePlan> dtos = null;
                QueryWrapper<WarningEventFailurePlan> wrapper4 = new QueryWrapper<>();
                if (StringUtils.isNotEmpty(event.getStation())) {
                    wrapper4.like("name", event.getStation());
                    dtos = warningEventFailurePlanMapper.selectList(wrapper4);
                }
                //if (StringUtils.isNotEmpty(device)) {
                //  wrapper.like("before_way", device);
                // }
                if (CollectionUtils.isNotEmpty(dtos)) {
                    event.setPlan(1);
                } else {
                    event.setPlan(0);
                }
                //信号缺失
                try {
                    List<WarningEventMissData> data = warningEventService.findMissData(t0121.getC0121FCode());
                    if (CollectionUtils.isEmpty(data)) {
                        event.setMissSignal(0);
                    } else {
                        event.setMissSignal(1);
                    }
                } catch (Exception e) {
                    event.setMissSignal(0);
                }
                this.saveOrUpdate(event);
                //warningEventMapper.insert(event);
            }
        }
    }

    @Override
    public void batchUploadWordPlan(MultipartFile file) throws Exception {

        //先删除基准库预案
        QueryWrapper<WarningEventFailurePlan> wrapper = new QueryWrapper<>();
        wrapper.eq("state_id", 1);
        warningEventFailurePlanMapper.delete(wrapper);

        //上传导入
        String filename = file.getOriginalFilename();
        String[] fileNames = filename.split("\\.");
        // 创建一个临时文件,方法结束后就会删除
        File newFile = File.createTempFile(fileNames[0], "." + fileNames[1]);
        InputStream inputStream = file.getInputStream();
        FileUtils.copyInputStreamToFile(inputStream, newFile);
        String absolutePath = newFile.getAbsolutePath();
        //Map<String, Object> map = new HashMap<>();
        FileInputStream in = new FileInputStream(absolutePath);//载入文档
        // 处理docx格式 即office2007以后版本
        //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
        XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
        Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
        int tableCount = 0;
        for (XWPFTable table : xwpf.getTables()) {
            tableCount++;
        }
        //System.out.println("表格总数：" + tableCount);
        while (it.hasNext()) {
            Map<String, Object> map = new HashMap<>();
            XWPFTable table = it.next();
            List<XWPFTableRow> rows = table.getRows();
            //读取每一行数据
            for (int i = 0; i < rows.size(); i++) {
                XWPFTableRow row = rows.get(i);
                //读取每一列数据
                List<XWPFTableCell> cells = row.getTableCells();
                String key1 = null;
                String key2 = "";
                String key3 = "";
                String key4;
                String key5 = "";

                String value1 = "";
                String value2 = "";
                String value3 = "";
                String value5 = "";

                for (int j = 0; j < cells.size(); j++) {
                    XWPFTableCell cell = cells.get(j);
                    if (cells.size() == 2) {
                        if (j == 0) {
                            key1 = cell.getText();
                        } else {
                            value1 = cell.getText().trim();
                        }
                    }

                    if (cells.size() == 4) {
                        if (j == 0) {
                            key2 = cell.getText();
                        } else if (j == 1) {
                            value2 = cell.getText().trim();
                        }
                        if (j == 2) {
                            key3 = cell.getText();
                        } else if (j == 3) {
                            value3 = cell.getText().trim();
                        }
                    }

                    if (cells.size() == 3) {
                        if (j == 1) {
                            key4 = cell.getText();
                            if (key4.equals("南网总调") || key4.equals("广东中调") || key4.equals("茂名调控")) {
                                key5 = "主要控制目标" + "/" + key4;
                            }
                            if (key4.equals("上报单位") || key4.equals("上报对象") || key4.equals("上报内容")) {
                                key5 = "事故信息上报" + "/" + key4;
                            }
                            if (key4.equals("发布单位") || key4.equals("发布对象") || key4.equals("发布内容")) {
                                key5 = "事故信息发布" + "/" + key4;
                            }
                        } else if (j == 2) {
                            value5 = cell.getText();
                        }
                    }
                }
                map.put(key1, value1);
                map.put(key2, value2);
                map.put(key3, value3);
                map.put(key5, value5);
                map.remove(null);
                map.remove("");
            }
            NodeSingle node = new NodeSingle();
            node.setAttrs(map);
            WarningEventFailurePlan plan = new WarningEventFailurePlan();
            Map<String, Object> attrs = node.getAttrs();
            String name = null;
            if (attrs.containsKey("事故预案名称")) {
                name = attrs.get("事故预案名称").toString();
            }
            plan.setName(name);
            for (String s : attrs.keySet()) {
                if (s.contains("编号")) {
                    plan.setNumber(attrs.get(s).toString());
                }
            }
            if (attrs.containsKey("负责单位")) {
                plan.setPlace(attrs.get("负责单位").toString());
            }
            if (attrs.containsKey("创建日期")) {
                plan.setCreateDate(attrs.get("创建日期").toString());
            }
            if (attrs.containsKey("编制人")) {
                plan.setProducer(attrs.get("编制人").toString());
            }
            if (attrs.containsKey("审核人")) {
                plan.setAuditor(attrs.get("审核人").toString());
            }
            if (attrs.containsKey("概述")) {
                plan.setSummary(attrs.get("概述").toString());
            }
            if (attrs.containsKey("事前运行方式")) {
                plan.setBeforeWay(attrs.get("事前运行方式").toString());
            }
            if (attrs.containsKey("故障设置")) {
                plan.setFaultSetting(attrs.get("故障设置").toString());
            }
            if (attrs.containsKey("事后运行方式")) {
                plan.setAfterWay(attrs.get("事后运行方式").toString());
            }
            if (attrs.containsKey("事后风险分析")) {
                plan.setAfterRisk(attrs.get("事后风险分析").toString());
            }
            if (attrs.containsKey("主要控制目标/南网总调")) {
                plan.setTotalNote(attrs.get("主要控制目标/南网总调").toString());
            }
            if (attrs.containsKey("主要控制目标/广东中调")) {
                plan.setMiddleNote(attrs.get("主要控制目标/广东中调").toString());
            }
            if (attrs.containsKey("主要控制目标/茂名调控")) {
                plan.setRegulation(attrs.get("主要控制目标/茂名调控").toString());
            }
            if (attrs.containsKey("事故处理过程及要点")) {
                plan.setProcess(attrs.get("事故处理过程及要点").toString());
            }
            if (attrs.containsKey("事故信息上报/上报单位")) {
                plan.setReportedPlace(attrs.get("事故信息上报/上报单位").toString());
            }
            if (attrs.containsKey("事故信息上报/上报内容")) {
                plan.setReportedObject(attrs.get("事故信息上报/上报内容").toString());
            }
            if (attrs.containsKey("事故信息上报/上报对象")) {
                plan.setReportedContent(attrs.get("事故信息上报/上报对象").toString());
            }
            if (attrs.containsKey("事故信息发布/发布单位")) {
                plan.setPublishPlace(attrs.get("事故信息发布/发布单位").toString());
            }
            if (attrs.containsKey("事故信息发布/发布内容")) {
                plan.setPublishObject(attrs.get("事故信息发布/发布内容").toString());
            }
            if (attrs.containsKey("事故信息发布/发布对象")) {
                plan.setPublishContent(attrs.get("事故信息发布/发布对象").toString());
            }
            if (attrs.containsKey("事故影响评估")) {
                plan.setAssess(attrs.get("事故影响评估").toString());
            }
            if (attrs.containsKey("备注")) {
                plan.setRemarks(attrs.get("备注").toString());
            }
            //类别
            if (name.contains("母线")) {
                plan.setCategory(2);
            }
            if (name.contains("全站")) {
                plan.setCategory(1);
            } else {
                plan.setCategory(3);
            }
            //级别
            String number = plan.getNumber();
            if (number.contains("较大")) {
                plan.setLevel(6);
            }
            if (number.contains("一般")) {
                plan.setLevel(7);
            }
            if (number.contains("一级")) {
                plan.setLevel(1);
            }
            if (number.contains("二级")) {
                plan.setLevel(2);
            }
            if (number.contains("三级")) {
                plan.setLevel(3);
            }
            if (number.contains("四级")) {
                plan.setLevel(4);
            }
            if (number.contains("五级")) {
                plan.setLevel(5);
            }
            plan.setStateId(1);
            //更新时间
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(date);
            plan.setUpdateTime(time);
            //厂站 分词
            StringReader reader = new StringReader(name);
            IKSegmenter ik = new IKSegmenter(reader, true);
            Lexeme lex;
            while ((lex = ik.next()) != null) {
                String text = lex.getLexemeText();
                if (text.contains("站") && !text.equals("全站")) {
                    //System.out.println("==========" + text);
                    plan.setStation(text);
                }
            }
            warningEventFailurePlanMapper.insert(plan);
        }
    }

    @Override
    public void windexAnalysis() {
        QueryWrapper<T0125IalmWindex> wrapper = new QueryWrapper<>();
        wrapper.like("C0125_DESC", "失压");
        List<T0125IalmWindex> t0125IalmWindices = t0125IalmWindexMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(t0125IalmWindices)) {
            for (T0125IalmWindex t0125 : t0125IalmWindices) {
                WarningEvent event = new WarningEvent();
                //主键id
                event.setEventId(t0125.getC0125WCode());
                //类型
                event.setEventType("异常告警");
                //时间
                String ymd = t0125.getC0125YMD().toString();
                String hmsms = t0125.getC0125HMSMS().toString();
                hmsms = String.format("%9s", hmsms).replace(" ", "0");
                StringBuffer buffer = new StringBuffer();
                buffer.append(ymd, 0, 4).append("-").append(ymd, 4, 6).append("-").append(ymd, 6, 8).append(" ").append(hmsms, 0, 2).append(":").append(hmsms, 2, 4).append(":").append(hmsms, 4, 6);
                event.setTime(buffer.toString());
                //厂站
                String c0125Desc = t0125.getC0125Desc();
                String[] split = c0125Desc.split("\\s+");
                List<String> collect = Arrays.stream(split).collect(Collectors.toList());

                if (collect.size() > 2) {
                    String desc = collect.get(collect.size() - 1);
                    event.setEventDescribe(desc.replaceAll("\\[.*?\\]", ""));
                    event.setPlan(0);
                }
                if (collect.size() == 2) {
                    //描述 删掉[]内容
                    String desc = collect.get(collect.size() - 1).replaceAll("\\[.*?\\]", "");
                    event.setEventDescribe(desc);
                    //删掉{}内容
                    String station = collect.get(0).replaceAll("\\{[^}]*\\}", "");
                    event.setStation(station);
                    //推荐预案
                    List<WarningEventFailurePlan> dtos = null;
                    QueryWrapper<WarningEventFailurePlan> wrapper4 = new QueryWrapper<>();
                    if (StringUtils.isNotEmpty(station)) {
                        wrapper4.like("name", station);
                        dtos = warningEventFailurePlanMapper.selectList(wrapper4);
                    }
                    //if (StringUtils.isNotEmpty(device)) {
                    //  wrapper.like("before_way", device);
                    // }
                    if (CollectionUtils.isNotEmpty(dtos)) {
                        event.setPlan(1);
                    } else {
                        event.setPlan(0);
                    }
                }
                if (collect.size() == 1) {
                    //描述
                    String desc = c0125Desc.replaceAll("\\{[^}]*\\}|\\[[^]]*\\]", "");
                    event.setEventDescribe(desc);
                    event.setPlan(0);
                }
                //设备
                Integer devId = t0125.getC0125FAULTDEVID();
                if (devId != null) {
                    QueryWrapper<T1211Device> wrapper2 = new QueryWrapper<>();
                    wrapper2.eq("C1211_DEVID", devId);
                    T1211Device t1211Device = t1211DeviceMapper.selectOne(wrapper2);
                    if (t1211Device != null) {
                        event.setDevice(t1211Device.getC1211DEVDESC());
                    }
                    //设备类型
                    if (t1211Device != null) {
                        String devtype = t1211Device.getC1216DEVTYPE();
                        QueryWrapper<T1216Devicetype> wrapper3 = new QueryWrapper<>();
                        wrapper3.eq("C1216_DEVTYPE", devtype);
                        T1216Devicetype devicetype = t1216DevicetypeMapper.selectOne(wrapper3);
                        if (null != devicetype) {
                            event.setDeviceType(devicetype.getC1216Devtypedesc());
                        }
                    }
                }

                //缺失信号
                List<WarningEventMissData> data = warningEventService.findMissData(t0125.getC0125WCode());
                if (CollectionUtils.isEmpty(data)) {
                    event.setMissSignal(0);
                } else {
                    event.setMissSignal(1);
                }
                this.saveOrUpdate(event);
                //warningEventMapper.insert(event);
            }
        }
    }

    //每10分钟刷新一下告警事件列表
    @Scheduled(cron = "0 */10 * * * ? ")
    public void warningEventCount() {
        log.info("告警事件-开始分析事故告警");
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        Integer localDate2 = Integer.valueOf(localDate.format(formatter));
        this.findexAnalysis(localDate2);
        log.info("告警事件-事故告警分析完成");
        log.info("告警事件-开始分析信号异常");
        this.windexAnalysis();
        log.info("告警事件-信号异常分析完成");
    }
}